#coding:utf-8
import re,os,sys
import datetime


###XXXX-01-01
####算日期不同

class DateTool(object):
    def __init__(self):
        self.stopwords = {}
        self.stopwords['未知'] = 1
        self.stopwords['其它'] = 1
        self.stopwords['其他'] = 1
        self.stopwords['暂无'] = 1
        self.stopwords['无'] = 1
        self.days_pattern = re.compile('[12][90][0-9]{2,2}-[01]?[0-9]-[0123]?[0-9]' )
        self.days_pattern2 = re.compile('[12][90][0-9]{2,2}年[01]?[0-9]月' )
        pass

    def get_year(self, day = "0000-00-00"):
        try:
            year = day[:4]
            if not year.isdigit():
                return None
            year = int(year)
            if year < 1900 or year > 2030:
                return None
            return year
        except :
            return None

        return None

    def get_diff_days(self, d1, d2):
        try:
            year = d1[:4]
            if not year.isdigit():
                return None
            year = int(year) 
            if year < 1900 or year > 2030:
                return None

            year = d2[:4]
            if not year.isdigit():
                return None
            year = int(year) 
            if year < 1900 or year > 2030:
                return None
            ori, dst = d1, d2
            d1 = datetime.datetime.strptime( d1, "%Y-%m-%d")
            d2 = datetime.datetime.strptime( d2, "%Y-%m-%d")
            diff = d1 - d2
            days = abs( diff.days )
            #日期不准
            if days < 60 and ori.endswith('-01-01'):
                if dst[5:7] != '12':
                    days = 60
            elif days < 60 and dst.endswith('-01-01'):
                if ori[5:7] != '12':
                    days = 60

            return days
        except Exception,e:
            return None
        return None

    def extract_str(self, d ):
        if d is None:
            return ''
        if isinstance(d, datetime.datetime):
            d = d.strftime('%Y-%m-%d')
            return d

        if isinstance(d, unicode):
            d = d.encode('utf-8', 'ignore')

        if not isinstance(d, str):
            return ''

        if len(d) == 14 and d[:8].isdigit() and d.endswith('-01-01'):
            d = d[:8]

        old = d
        d = d.replace("'", '').replace('"', ' ').strip().replace("(", ' ').replace(")", " ").replace("（", " ").replace('）', ' ')
        d = d.replace('年', '-').replace('月', '-').replace('日', '-')
        d = d.replace('/', '-')
        d = d.strip()

        if d.endswith('-'):
            d = d[:-1].strip()
        if len(d) == 4 and d.isdigit():
            if int(d) <= 2030 and int(d) > 1900:
                d = d + "-01-01"
        elif len(d) == 7 and d[:4].isdigit() and d[4] == '-' and d[-2:].isdigit():
            y = int(d[:4])
            m = int(d[-2:])
            if y < 2030 and y > 1900 and m >= 1 and m <= 12:
               d += "-01"
        elif len(d) == 8 and d.isdigit():
            y = int(d[:4])
            m = int(d[4:6])
            x = int(d[6:])
            if y >= 1900 and y <= 2030 and m <= 12 and m >= 1 and x >= 1 and x <= 31:
                d = '%0.4d-%0.2d-%0.2d' % (y, m,x)

                if x <= 28: 
                    return d
                if m != 2 and x <= 30:
                    return d

                try:
                    d = datetime.datetime.strptime( d , "%Y-%m-%d")
                    d = d.strftime('%Y-%m-%d')
                    return d
                except:
                    return ''
                    pass

        days = self.days_pattern.findall( d )
        #days = re.findall('[12][90][0-9]{2,2}-[01]?[0-9]-[0123]?[0-9]', d )
        #if len(days) == 0:
        #    return ''
        results = []
        for day in days:
            year = day[:4]
            if not year.isdigit():
                continue
            year = int(year)
            if year > 2030 or year < 1900: continue
            try:
                d = datetime.datetime.strptime( day , "%Y-%m-%d")
                d = d.strftime('%Y-%m-%d')
                results.append( d ) 
            except Exception,e:
                results.append( str(year)+"-01-01" )
                continue

        if len(results) > 0:
            return ','.join( results )

        if not results:
            days = self.days_pattern2.findall( old )
            #days = re.findall('[12][90][0-9]{2,2}年[01]?[0-9]月', old )
            for d in days:
                d = d.replace('年', '-').replace('月', '')
                year = int(d[:4])
                if year < 1900: continue
                if year > 2030: continue
                m = int(d[5:])
                if m < 1 : m = 1
                if m > 12 : m = 1
                d = '%0.4d-%0.2d-01' % (year, m )
                results.append( d )
            
        return ','.join( results )

    def score_year( self, album, video):
        if not album or not video:
            return None
        xyears, yyears = [], []
        if isinstance(album, int):
            if album <= 1900:
                return None
            if album >= 2030:
                return None
            xyears.append( album )
        if isinstance(video, int):
            if video <= 1900:
                return None
            if video >= 2030:
                return None
            yyears.append( video )

        if isinstance(album, str) or isinstance( album, unicode):
            xdays = self.extract_str( album ).split(',')
            for d in xdays:
                year = d[:4]
                if not year.isdigit():
                    continue
                xyears.append( int(year) )

        if isinstance(video, str) or isinstance( video, unicode):
            ydays = self.extract_str( video ).split(',')
            for d in ydays:
                year = d[:4]
                if not year.isdigit():
                    continue
                yyears.append( int(year) )

        if not xyears or not yyears:
            return None
        year_diff = 1000
        for y1 in xyears:
            for y2 in yyears:
                diff = abs(y1-y2)
                if diff == 0: 
                    return 0
                if year_diff > diff:
                    year_diff = diff
        if year_diff >= 10:
            year_diff  = 10 

        return year_diff

    def score_datetime( self, album, video):
        if not album or not video:
            return 0, None
        if not isinstance( video, str) and not isinstance(video, unicode):
            return 0, None
        if not isinstance( album, str) and not isinstance( album, unicode):
            return 0, None

        xdays = self.extract_str( album )
        ydays = self.extract_str( video )
        #print "###",xdays
        #print "###",ydays
        if not xdays or not ydays:
            return 0, None
        xdays = xdays.split(',') 
        ydays = ydays.split(',') 

        days_diff = 1000000
        for x in xdays:
            for y in ydays: 
                days = self.get_diff_days( x, y )
                if days < days_diff:
                    days_diff = days
                if days_diff <= 0:
                    break
        if days_diff <= 5:
            return 1, days_diff
        elif days_diff <= 60:
            return 0, days_diff
        else:
            return -1, days_diff

        return 0, None

#日期工具
dateTool = DateTool()

def test():
    daystr = [ "2004'", '2005年"', "(2006年7月)（2004年3月）", '2004', '1986-01', '1987年', '1988-13-01', '2015-12-01', '2014-1-15', '"2018-10-01(台湾)',
    "2006年7月", "1890", "1935年10月8日", "1949-1-10" ]
    #f = open('testcase/dates.txt', 'rb')
    #for d in f:
    for d in daystr:
        d = d.strip()
        if d == "":continue
        print '###', d
        day =  dateTool.extract_str( d )
        if day: print day
        #print dateTool.score_datetime(d, d)
        print
    pass
def test_day():
    pairs = [('2015-10-10', '2016'), ("'2014-03-14'", "2014-03-14"), ("'2014-03-14'", "2014-01-14'"), ("1999-01-01", "2006"), 
    ("2008-10-01","2015-05-01"), ("2008年10月-1", "2015-05-20"), ("20181004", "2017-05-01 2018-10-05"), ("1985-10-5", "2010-3-5"), ("2010/10/10", "2005/09/01"), ("1945年4月1日", "1935-3-5"), ("一年前", ""), (None, "1980")]
    pairs = [('2011', '')]
    pairs = [('2015-12-29', '2016-01-07')]
    for pair in pairs:
        x, y = pair
        print x,"###", y
        print dateTool.score_datetime(x,y )
        print 'YEAR',dateTool.score_year(x,y )
        print 
        
    pass

if __name__ == "__main__":
    day =  dateTool.extract_str( '20111203-01-01' )
    #print day
    #test()
    test_day()
